package com.groot.common.web.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.groot.common.exception.BusinessException;
import com.groot.common.utils.LogUtils;
import com.groot.common.web.exception.model.ExceptionResponse;

@ControllerAdvice
public class DefaultExceptionHandler {

	@ExceptionHandler
	public ModelAndView processUnauthenticatedException(
			HttpServletRequest request, Exception ex) {
		LogUtils.logError("程序异常", ex);
		
		ExceptionResponse exceptionResponse = ExceptionResponse.from(ex);
		request.setAttribute("ex", ex);

		ModelAndView mv = new ModelAndView();
		mv.addObject("error", exceptionResponse);

		// 根据不同错误转向不同页面
		if (ex instanceof BusinessException) {
			mv.setViewName("exception/exception-business");
		} else {
			mv.setViewName("exception/exception");
		}
		return mv;
	}

}
